package objectStream;

import org.junit.Test;

import java.io.*;

/*
* 对象流:
* 将对象保存到磁盘文件中,或将磁盘文件中的数据转换成程序中的对象
* */
public class ObjectStreamTest {

    /*
    * 对象输出流:对象的序列化
    *
    * 自定义的对象要序列化和反序列化,需要实现Serializable
    * */
    @Test
    public void test1(){
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream("object.dat"));

            objectOutputStream.writeObject(new String("中国"));
            objectOutputStream.writeObject(new Person("xiaoming",12));
            objectOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
     * 对象输入流:对象的反序列化
     * */
    @Test
    public void test2(){
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream("object.dat"));

            String str = (String) objectInputStream.readObject();
            System.out.println(str);//中国

            Person xiaoming = (Person) objectInputStream.readObject();
            System.out.println(xiaoming);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
